package com.kma.ncpractice2013.servlets;

import com.kma.ncpractice2013.facade.MailFacade;
import com.kma.ncpractice2013.facade.MailFacadeImpl;
import org.expressme.openid.*;
import org.json.JSONObject;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.io.*;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.UUID;


/**
 * User: Viktor
 * Date: 10/24/13
 */

public class OrderServlet extends HttpServlet                   //DO NOT USE
{

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
	    response.setContentType("text/html;charset=UTF-8");
	    JSONObject neighbourhood = new JSONObject(URLDecoder.decode(request.getParameter("neighbourhood"), "UTF-8"));
	    JSONObject hotelDesc = new JSONObject(URLDecoder.decode(request.getParameter("hotelDesc"), "UTF-8"));
	    double price = Double.parseDouble(request.getParameter("price"));
		int adults = Integer.parseInt(request.getParameter("adults"));
	    int children = Integer.parseInt(request.getParameter("children"));

	    Date checkin = Date.valueOf(request.getParameter("checkindate"));
	    Date checkout = Date.valueOf(request.getParameter("checkoutdate"));

	    Connection conn = null;

	    try
	    {
		    Context ctx = new InitialContext();
		    DataSource ds = null;
		    ds = (DataSource) ctx.lookup("jdbc/security");
		    conn = ds.getConnection();
		    HttpSession session = request.getSession(false);
		    String isLoggedin = null;
		    if (session != null)
		    {
			    isLoggedin = (String) session.getAttribute("auth");
		    }
		    String login = null;
		    if (isLoggedin != null && isLoggedin.equals("true"))
		    {
			    login = (String) session.getAttribute("username");
		    } else
		    {
			    login = request.getParameter("username");
			    PreparedStatement ps = null;
			    try
			    {
				    ps = conn.prepareStatement("select ID from USERS where LOGIN = ?"); //DAO!!!1
				    ps.setString(1, login);
				    ResultSet execute = ps.executeQuery();

				    if(execute.next())
				    {
					    out.print("please log in");
					    out.println("<a href=\"login.jsp\">login</a>");
					    return;
				    }
			    }
			    catch (Exception e)
			    {
				    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
				    response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/error.jsp"));
			    }
		    }


		    String token = UUID.randomUUID().toString();


		    MailFacade mail = new MailFacadeImpl();
		    String email = login;
		    String subject = "Reservation System order confirmation";
		    String letter = "Click on the following link to confirm your order.\n" +
				                    MailFacadeImpl.home + "/orderconfirmation.jsp?token=" + token +               //fix path
				                    "\nLink is valid for 1 day.";
		    try
		    {
			    mail.sendLetter(email, subject, letter);

		    } catch (Exception e)
		    {
			    out.print(e.getMessage());
			    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
			    response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/error.jsp"));
		    }
		    Date d = new Date(System.currentTimeMillis());

		    PreparedStatement location_insert = conn.prepareStatement("INSERT INTO LOCATIONS (CENTROID, COUNTRY, CITY, STATE, NAME) VALUES (?, ?, ?, ?, ?)");

		    location_insert.setString(1, neighbourhood.getString("Centroid"));
		    location_insert.setString(2, neighbourhood.getString("Country"));
		    location_insert.setString(3, neighbourhood.getString("City"));
		    location_insert.setString(4, neighbourhood.getString("State"));
		    location_insert.setString(5, neighbourhood.getString("Name"));
		    location_insert.execute();

		    PreparedStatement getId = conn.prepareStatement("SELECT ID FROM LOCATIONS WHERE NAME = ?");
		    getId.setString(1, neighbourhood.getString("Name"));
		    ResultSet rs = getId.executeQuery();
		    rs.next();
		    int locationId = rs.getInt("ID");

		    PreparedStatement ps = conn.prepareStatement("select ID FROM USERS WHERE LOGIN = ?");
		    ps.setString(1, login);
		    rs = ps.executeQuery();
		    rs.next();
		    int userId = rs.getInt("ID");


		    PreparedStatement order_insert = conn.prepareStatement("INSERT INTO ORDERS (USER_ID, LOCATION_ID, ROOMS, ADULTS, CHILDREN, NIGHTS, STARS, DATE_OF_ORDER, CHECK_IN_DATE, CHECK_OUT_DATE, CONFIRMATION_TOKEN, PRICE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
		    order_insert.setInt(1, userId);
		    order_insert.setInt(2, locationId);
		    order_insert.setInt(3, hotelDesc.getInt("Rooms"));
		    order_insert.setInt(4, adults);
		    order_insert.setInt(5, children);
		    order_insert.setInt(6, hotelDesc.getInt("Nights"));
		    order_insert.setString(7, hotelDesc.getString("StarRating"));
		    order_insert.setDate(8, d);
		    order_insert.setDate(9, checkin);
		    order_insert.setDate(10, checkout);
		    order_insert.setString(11, token);
		    order_insert.setDouble(12, price);

			order_insert.execute();


		    out.print("Confirmation letter has been sent to " + login);
		    //out.println("<a href=\"login.jsp\">login</a>");
		    //response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/login.jsp"));


	    }
	    catch(Exception e)
	    {
		    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
		    response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/error.jsp"));
	    }
	    finally
	    {
		    try
		    {
			    conn.close();
		    } catch (Exception e)
		    {
			    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
			    response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/error.jsp"));
		    }
	    }







    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}
